package rabbitmq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建连接⼯⼚
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost(Constants.HOST);//ip 默认值localhost
        factory.setPort(Constants.PORT); //默认值5672
        factory.setVirtualHost(Constants.VIRTUAL_HOST);//虚拟机名称, 默认 /
        factory.setUsername(Constants.USER_NAME);//⽤⼾名,默认guest
        factory.setPassword(Constants.PASSWORD);//密码, 默认guest
        //3. 创建连接Connection
        Connection connection = factory.newConnection();
        //4. 创建channel通道
        Channel channel = connection.createChannel();
        //5. 声明交换机
        channel.exchangeDeclare(Constants.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT,true);
        //6. 声明队列
        channel.queueDeclare(Constants.DIRECT_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.DIRECT_QUEUE2,true,false,false,null);
        //7. 交换机和队列绑定
        channel.queueBind(Constants.DIRECT_QUEUE1,Constants.DIRECT_EXCHANGE,"a");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"a");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"b");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"c");
        //8. 发布消息
        String msg1 = "Hello direct queue,my routingkey is a~";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"a",null,msg1.getBytes());
        String msg2 = "Hello direct queue,my routingkey is b~";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"b",null,msg2.getBytes());
        String msg3 = "Hello direct queue,my routingkey is c~";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"c",null,msg3.getBytes());
        System.out.println("发布消息成功");
        //9. 资源释放
        channel.close();
        connection.close();
    }
}
